package com.pc.store.controller;


import com.pc.store.controller.ex.*;
import com.pc.store.entity.User;
import com.pc.store.service.IUserService;
import com.pc.store.service.ex.InsertException;
import com.pc.store.service.ex.UsernameDuplicatedException;
import com.pc.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("users")
public class UserController extends BaseController {
    @Autowired
    private IUserService iUserService;

    @RequestMapping("reg")
//    @ResponseBody 将Json数据写入响应包中
    public JsonResult<Void> reg(User user) {
        iUserService.reg(user);

        return new JsonResult<>(OK);
    }

    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session) {
        User data = iUserService.login(username, password);

        /*向session对象中完成数据的绑定,session全局的*/
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());

        /*获取session中绑定的数据*/
//        System.out.println(getuidFromSession(session));
//        System.out.println(getUsernameFromSession(session));

        return new JsonResult<User>(OK, data);
    }

    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session) {
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        iUserService.changePassword(uid, username, oldPassword, newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session) {
        User data = iUserService.getByUid(getuidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(User user, HttpSession session) {
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        iUserService.changeInfo(uid, username, user);
        return new JsonResult<>(OK);
    }

    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file) {
        /**
         * 首先传参一定要和前端的命名一致，比如file
         * 如果类型是MultipartFile并且参数名和前端上传文件的name相同,则会自动把整体的数据包传递给file
         */
        if (file.isEmpty()) {
            throw new FileEmptyException("文件为空");
        }
        if (file.getSize() > AVATAR_MAX_SIZE) {
            throw new FileSizeException("文件超出大小限制");

        }
        String contentType = file.getContentType();

        if (!AVATAR_TYPE.contains(contentType)) {
            throw new FileTypeException("文件类型不支持");
        }

        //上传的文件放在.../upload/文件.png
        String parent = session.getServletContext().getRealPath("upload");

        System.out.println(parent);

        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //使用新字符串作为文件名，UUID，避免覆盖
        String originFilename = file.getOriginalFilename();

        System.out.println("OriginFilename: " + originFilename);

        int index = originFilename.lastIndexOf(".");
        String suffix = originFilename.substring(index);
        //filename形如SAFS1-56JHIOHI-HIUGHUI-5565TYRF.png
        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
        //dir目录下创建文件
        File dest = new File(dir, filename);
            /*
            先捕获FileStateException再捕获IOException是
            因为后者包含前者,如果先捕获IOException那么
            FileStateException就永远不可能会被捕获
            */
        try {
            file.transferTo(dest);
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        String avatar = "/upload/" + filename;
        iUserService.changeAvatar(uid, avatar, username);


        return new JsonResult<>(OK, avatar);

    }
}
